package com.tubang.organization.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tubang.common.redis.RedisGeneratekeyUtils;
import com.tubang.common.util.BeanMapper;
import com.tubang.common.util.DateFormatUtils;
import com.tubang.common.util.EncryptorUtil;
import com.tubang.common.util.GsonQuick;
import com.tubang.common.util.MsgCode;
import com.tubang.common.util.ResultData;
import com.tubang.common.util.StringUtils;
import com.tubang.component.entity.AddressEntity;
import com.tubang.component.entity.CompanyEntity;
import com.tubang.component.entity.UserEntity;
import com.tubang.component.service.IAddressService;
import com.tubang.component.service.ICompanyService;
import com.tubang.component.service.IRedisService;
import com.tubang.component.service.IUserService;
import com.tubang.component.util.RequestUtil;
import com.tubang.component.vo.AddressVo;
import com.tubang.component.vo.CompanyVo;
import com.tubang.component.vo.UserVo;
import com.tubang.organization.dto.ApplyJoinCompanyDto;
import com.tubang.organization.dto.IdentityAuditDto;
import com.tubang.organization.dto.UserDto;
import com.tubang.organization.vo.UserAppInfoVo;
import com.tubang.organization.vo.UserDetailVo;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author wsl
 * @since 2017-11-30
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private IUserService userService;
    @Resource
    private IAddressService addressService;
    @Resource
    private ICompanyService companyService;
    @Resource
    private IRedisService redisService;

    /**
     * 用户注册
     *
     * @return
     */
    @PostMapping(value = "register")
    @Transactional
    public ResultData register(HttpServletRequest request, HttpServletResponse response) {
        String receivePostJson = RequestUtil.receivePostJson(request);
        UserVo userVo = GsonQuick.toObject(receivePostJson, UserVo.class);
        AddressVo addressVo = GsonQuick.toObject(receivePostJson, AddressVo.class);
        CompanyVo companyVo = GsonQuick.toObject(receivePostJson, CompanyVo.class);
        String verifyInput = GsonQuick.getString(receivePostJson, "verifyInput");

        try {
            // 判断验证码
            if (StringUtils.isBlank(verifyInput)) {
                return ResultData.result(false).setMsg(MsgCode.USER_CODE_IS_EMPTY_DESC).setStatus(MsgCode.USER_CODE_IS_EMPTY);
            }
            // 判断验证码是否相等
            if (!redisService.exists(RedisGeneratekeyUtils.GeneratedStringValidateCodeKey(verifyInput.toUpperCase()))) {
                return ResultData.result(false).setMsg(MsgCode.USER_CODE_IS_ERROR_DESC).setStatus(MsgCode.USER_CODE_IS_ERROR);
            }

            //校验手机号是否注册过
            EntityWrapper<UserEntity> userEntityWrapper = new EntityWrapper<UserEntity>();
            userEntityWrapper.eq("mobile", userVo.getMobile());
            int conut = userService.selectCount(userEntityWrapper);
            if (conut > 0) {
                //用户存在
                return ResultData.result(false).setMsg(MsgCode.USER_MOBILE_IS_REGISTER_DESC).setCode(MsgCode.USER_MOBILE_IS_REGISTER);
            }

            //保存地址信息
            AddressEntity addressEntity = BeanMapper.map(addressVo, AddressEntity.class);
            boolean addressEntityinsert = addressService.insert(addressEntity);
            if (!addressEntityinsert) {
                return ResultData.result(false).setMsg(MsgCode.ADDRESS_FAIL_IS_REGISTER_DESC).setStatus(MsgCode.ADDRESS_FAIL_IS_REGISTER).setData(addressEntity);
            }

            String userType = userVo.getUserType();

            //保存公司信息
            CompanyEntity companyEntity = BeanMapper.map(companyVo, CompanyEntity.class);
            companyEntity.setAddressId(addressEntity.getId());
            companyEntity.setPhone(userVo.getMobile());
            companyEntity.setType(userType);
            companyEntity.setName(userVo.getName());
            boolean companyEntityinsert = companyService.insert(companyEntity);
            if (!companyEntityinsert) {
                return ResultData.result(false).setMsg(MsgCode.COMPANY_FAIL_IS_REGISTER_DESC).setStatus(MsgCode.COMPANY_FAIL_IS_REGISTER).setData(companyEntity);
            }
            //保存用户信息
            UserEntity user = BeanMapper.map(userVo, UserEntity.class);
            user.setCompanyId(companyEntity.getId());
            /**
             * 给用户密码加密
             */
            user.setPassword(EncryptorUtil.AesEncrypt(userVo.getPassword()));
            user.setRoleId(userType);

            // 判断注册用户的类型
            if (StringUtils.equals("60003", userType) || StringUtils.equals("60004", userType)) {
                // 待审核
                user.setStatus("801");
            }
            userService.insertOrUpdate(user);
            return ResultData.result(true).setMsg(MsgCode.DEFAULT_SUCCESS_MSG).setData(user).setStatus(MsgCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[user]<== method[register], 用户注册失败:[{}]", e.getMessage());
            return ResultData.result(false).setMsg(MsgCode.DEFAULT_ERROR_MSG).setCode(MsgCode.ERROR);
        }
    }


    /**
     * 平台功能-会员管理
     *
     *
     * @return ResultData 返回类型
     * @throws
     * @Title selectByUserId
     */
    @PostMapping(value = "selectUserList")
    public ResultData selectUserList(HttpServletRequest request, HttpServletResponse response) {
        try {
            String receivePostJson = RequestUtil.receivePostJson(request);
            UserDto userDto = GsonQuick.toObject(receivePostJson, UserDto.class);
            UserEntity userEntity = BeanMapper.map(userDto, UserEntity.class);
            EntityWrapper<UserEntity> wrapper = new EntityWrapper<>(userEntity);
            wrapper.in("user_type", userDto.getUserTypes());
            Page<UserEntity> page = userService.selectPage(new Page<>(userDto.getPage(), userDto.getRows()), wrapper);
            int totalCount = userService.selectCount(wrapper);
            List<UserEntity> userEntitys = page.getRecords();
            List<UserDetailVo> userDetailVos = new ArrayList<UserDetailVo>();
            for (UserEntity entity : userEntitys) {
                UserDetailVo userDetailVo = new UserDetailVo();
                userDetailVo.setUserId(entity.getId());
                userDetailVo.setUserRealName(entity.getRealName());
                userDetailVo.setUserMobile(entity.getMobile());
                userDetailVo.setUserType(entity.getUserType());
                userDetailVo.setStatus(entity.getStatus());
                userDetailVo.setResgistTime(DateFormatUtils.formatDate(entity.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
                CompanyEntity company = companyService.selectById(entity.getCompanyId());
                if (company == null) {
                    userDetailVos.add(userDetailVo);
                    continue;
                }
                AddressEntity addressEntity = addressService.selectById(company.getAddressId());
                if (addressEntity != null) {
                    BeanMapper.copy(addressEntity, userDetailVo);
                    userDetailVo.setAddressId(addressEntity.getId());
                }

                userDetailVo.setCompanyId(company.getId());
                userDetailVo.setCompanyName(company.getName());
                userDetailVo.setCompanyType(company.getType());
                userDetailVo.setCompanyTypeDesc(company.getTypeDesc());

                userDetailVos.add(userDetailVo);
            }
            logger.info("[user]<== method[selectUserList], 查询结果：{}", GsonQuick.getGson().toJson(page));
            return ResultData.result(true).setTotalCount(totalCount).setData(userDetailVos);
        } catch (Exception e) {
            logger.error("[user]<== method[selectUserList], 查询失败：{}", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }

    /**
     * 平台功能-会员详情展示
     * @param form
     * @return ResultData 返回类型
     * @throws
     * @Title selectByUserId
     */
    @GetMapping(value = "selectUserById")
    public ResultData selectUserById(UserDto userDto) {
        logger.info("[user]==> method[selectUserById],请求userId：{}", GsonQuick.getGson().toJson(userDto));
        try {
            UserEntity user = userService.selectById(userDto.getId());
            CompanyEntity company = companyService.selectById(user.getCompanyId());
            AddressEntity addressEntity = addressService.selectById(company.getAddressId());
            UserDetailVo userDetailVo = BeanMapper.map(addressEntity, UserDetailVo.class);
            if (addressEntity != null) {
                userDetailVo.setAddressId(addressEntity.getId());
            }
            userDetailVo.setUserId(user.getId());
            userDetailVo.setUserRealName(user.getRealName());
            userDetailVo.setUserMobile(user.getMobile());
            userDetailVo.setCompanyId(company.getId());
            userDetailVo.setCompanyName(company.getName());
            userDetailVo.setCompanyType(company.getType());
            userDetailVo.setCompanyTypeDesc(company.getTypeDesc());
            userDetailVo.setStatus(user.getStatus());
            return ResultData.result(true).setData(userDetailVo);
        } catch (Exception e) {
            logger.error("[user]<== method[selectUserById], 查询失败：{}", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }
    
    
    /**
     * 根据主键查询用户信息
     * @Title selectById 
     * @Description 根绝id查询用户信息
     * @param id
     * @return ResultData 返回类型 
     * @throws
     */
    @GetMapping(value = "selectById")
    public ResultData selectById(@RequestParam(required = true) String id) {
    	try {
    		UserEntity user = userService.selectById(id);
    		return ResultData.result(true).setData(user);
    	} catch (Exception e) {
    		logger.error("[user]<== method[selectById], 查询失败：{}", e.getMessage());
    		e.printStackTrace();
    		return ResultData.result(false).setData(e);
    	}
    }


    /**
     * 平台功能-会员编辑
     *
     * @param form
     * @return ResultData 返回类型
     * @throws
     * @Title selectByUserId
     */
    @PostMapping(value = "update")
    @Transactional
    public ResultData update(HttpServletRequest request, HttpServletResponse response) {
        try {
            String receivePostJson = RequestUtil.receivePostJson(request);
            UserDetailVo userDetailVo = GsonQuick.toObject(receivePostJson, UserDetailVo.class);
            //用户
            UserEntity user = new UserEntity();
            user.setId(userDetailVo.getUserId());
            user.setMobile(userDetailVo.getUserMobile());
            user.setStatus(userDetailVo.getStatus());
            user.setRealName(userDetailVo.getUserRealName());
            userService.updateById(user);
            //公司
            CompanyEntity company = new CompanyEntity();
            company.setId(userDetailVo.getCompanyId());
            company.setName(userDetailVo.getCompanyName());
            //company.setType(userDetailVo.getCompanyType());
            //company.setTypeDesc(userDetailVo.getCompanyTypeDesc());
            companyService.updateById(company);
            //地址信息
            AddressEntity addressEntity = GsonQuick.toObject(receivePostJson, AddressEntity.class);
            addressEntity.setId(userDetailVo.getAddressId());
            addressService.updateById(addressEntity);

            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[user]<== method[update], 查询失败：{}", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }


    /**
     * 用户手机号校验
     *
     * @return
     */
    @PostMapping(value = "checkUserMobile")
    public ResultData checkUserMobile(HttpServletRequest request, HttpServletResponse response) {
        String receivePostJson = RequestUtil.receivePostJson(request);
        String mobile = GsonQuick.getString(receivePostJson, "mobile");
        try {
            EntityWrapper<UserEntity> userEntityWrapper = new EntityWrapper<UserEntity>();
            userEntityWrapper.eq("mobile", mobile);
            int conut = userService.selectCount(userEntityWrapper);
            if (conut > 0) {
                //用户存在
                return ResultData.result(false).setMsg(MsgCode.USER_MOBILE_IS_REGISTER_DESC).setCode(MsgCode.USER_MOBILE_IS_REGISTER);
            }
            //用户不存在，可以注册
            return ResultData.result(true);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[user]<== method[checkUserMobile], 校验手机号失败:[{}]", e.getMessage());
            return ResultData.result(false).setMsg(MsgCode.DEFAULT_ERROR_MSG);
        }
    }

    /**
     * app - 审核
     * @param applyJoinCompany
     * @param 设定文件
     * @return ResultData 返回类型
     * @throws
     * @Title applyJoinCompany
     * @Description app - 审核
     */
    @PostMapping(value = "applyJoinCompanyAudit")
    public ResultData applyJoinCompanyAudit(HttpServletRequest request, HttpServletResponse response) {
        try {
        	String receivePostJson = RequestUtil.receivePostJson(request);
        	ApplyJoinCompanyDto applyJoinCompany = GsonQuick.toObject(receivePostJson, ApplyJoinCompanyDto.class);
            UserEntity user = userService.selectById(applyJoinCompany.getId());
            CompanyEntity company = companyService.selectById(applyJoinCompany.getCompanyId());
            if (user != null && company != null) {
                user.setCompanyId(company.getId());
                user.setName(company.getName());
                user.setStatus(applyJoinCompany.getStatus());
                userService.updateById(user);
                return ResultData.result(true);
            } else {
                return ResultData.result(false).setCode(MsgCode.USERORCOMPANY_IS_NOT_EXIST).setMsg(MsgCode.USERORCOMPANY_IS_NOT_EXIST_DESC);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[user]<== method[applyJoinCompanyAudit], 申请加入公司或者更换公司失败:[{}]", e.getMessage());
            return ResultData.result(false).setData(e);
        }
    }

    /**
     * @param applyJoinCompany
     * @param 设定文件
     * @return ResultData 返回类型
     * @throws
     * @Title applyJoinCompany
     * @Description app - 申请加入公司或者更换公司
     */
    @PostMapping(value = "applyJoinCompany")
    public ResultData applyJoinCompany(HttpServletRequest request, HttpServletResponse response) {
        String receivePostJson = RequestUtil.receivePostJson(request);
        ApplyJoinCompanyDto applyJoinCompany = GsonQuick.toObject(receivePostJson, ApplyJoinCompanyDto.class);
        try {
            UserEntity user = userService.selectById(applyJoinCompany.getId());
            CompanyEntity company = companyService.selectById(applyJoinCompany.getCompanyId());
            if (user != null && company != null) {
                user.setCompanyId(company.getId());
                user.setName(company.getName());
                user.setStatus(applyJoinCompany.getStatus());
                userService.updateById(user);
                return ResultData.result(true);
            } else {
                return ResultData.result(false).setCode(MsgCode.USERORCOMPANY_IS_NOT_EXIST).setMsg(MsgCode.USERORCOMPANY_IS_NOT_EXIST_DESC);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[user]<== method[applyJoinCompany], 申请加入公司或者更换公司失败:[{}]", e.getMessage());
            return ResultData.result(false).setData(e);
        }
    }


    /**
     * @param applyJoinCompany
     * @param 设定文件
     * @return ResultData 返回类型
     * @throws
     * @Title applyJoinCompany
     * @Description app - 个人信息认证
     */
    @PostMapping(value = "identityAudit")
    public ResultData identityAudit(HttpServletRequest request, HttpServletResponse response) {
        String receivePostJson = RequestUtil.receivePostJson(request);
        IdentityAuditDto identityAudit = GsonQuick.toObject(receivePostJson, IdentityAuditDto.class);
        try {
            UserEntity user = BeanMapper.map(identityAudit, UserEntity.class);
            user.setUpdateTime(new Date());
            userService.updateById(user);
            return ResultData.result(true);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[user]<== method[identityAudit], 申请加入公司或者更换公司失败:[{}]", e.getMessage());
            return ResultData.result(false).setData(e);
        }
    }

    /**
     * 完善用户信息
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "insertOrUpdateUserInfo")
    public ResultData insertOrUpdateUserInfo(HttpServletRequest request, HttpServletResponse response) {
        String receivePostJson = RequestUtil.receivePostJson(request);
        UserAppInfoVo userAppInfoVo = GsonQuick.toObject(receivePostJson, UserAppInfoVo.class);
        try {
            EntityWrapper<UserEntity> userEntityWrapper = new EntityWrapper<UserEntity>();
            userEntityWrapper.eq("mobile", userAppInfoVo.getMobile());
            UserEntity userEntity = userService.selectOne(userEntityWrapper);
            if (userEntity == null) ResultData.result(true);
            userEntity.setEmail(userAppInfoVo.getEmail());
            userEntity.setHeadUrl(userAppInfoVo.getHeadUrl());
            userEntity.setNikeName(userAppInfoVo.getNikeName());
            userEntity.setBirthday(userAppInfoVo.getBirthday());
            userEntity.setSex(userAppInfoVo.getSex());
            userEntity.setRealName(userAppInfoVo.getRealName());
            userService.insertOrUpdate(userEntity);
            return ResultData.result(true);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[user]<== method[insertOrUpdateUserInfo],完善用户信息失败 :[{}]", e.getMessage());
            return ResultData.result(false).setData(e);
        }
    }

    /**
     *  app-物流转个人
     * @Title updateUserStatus 
     * @Description
     * @param request
     * @param response
     * @return ResultData 返回类型 
     * @throws
     */
    @PostMapping(value = "updateUserById")
    public ResultData updateUserStatus(HttpServletRequest request, HttpServletResponse response) {
        String receivePostJson = RequestUtil.receivePostJson(request);
        UserVo userVo = GsonQuick.toObject(receivePostJson, UserVo.class);
        try {
            UserEntity entity = BeanMapper.map(userVo, UserEntity.class);
			userService.updateById(entity);
            return ResultData.result(true);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[user]<== method[updateUserStatus],app-物流转个人失败:[{}]", e.getMessage());
            return ResultData.result(false).setData(e);
        }
    }
    
    /**
     * 查询用户信息
     *
     * @param mobile
     * @return
     */
    @GetMapping(value = "queryUserInfo")
    public ResultData queryUserInfo(@RequestParam String mobile) {
    	try {
    		EntityWrapper<UserEntity> userEntityWrapper = new EntityWrapper<UserEntity>();
    		userEntityWrapper.eq("mobile", mobile);
    		UserEntity userEntity = userService.selectOne(userEntityWrapper);
    		BeanMapper.map(userEntity, UserAppInfoVo.class);
    		return ResultData.result(true).setData(userEntity);
    	} catch (Exception e) {
    		e.printStackTrace();
    		logger.error("[user]<== method[identityAudit], 申请加入公司或者更换公司失败:[{}]", e.getMessage());
    		return ResultData.result(false).setData(e);
    	}
    }

    public static void main(String[] args) {
        //重置密码
        String aesEncrypt = EncryptorUtil.AesEncrypt("123456");
        System.out.println(aesEncrypt);
//		String json = "{\n" + 
//				"\"userType\": \"0\",\n" + 
//				"\"districtName\": \"\"\n" + 
//				"}";
//		String verifyInput = GsonQuick.getString(json, "userType");
//		System.out.println(verifyInput);
    }

}
